package com.lsec.springbootinit.model.common;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.lsec.springbootinit.exception.enums.TypicalCode;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;


/**
 * 统一返回
 *
 * @author Cherry
 * @date 2023-03-03 14:42
 */

@Schema(description = "统一返回")
@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class CommonResult<T> {

    @Schema(hidden = true)
    public static final int FAIL = TypicalCode.INTERNAL_SERVER_ERROR_500.getCode();
    @Schema(hidden = true)
    public static final int SUCCESS = TypicalCode.SUCCESS_200.getCode();

    /**
     * 代码
     */
    @Schema(description = "返回码")
    private Integer code;
    /**
     * 错误提示，用户可阅读
     */
    @Schema(description = "错误提示，用户可阅读")
    private String msg;
    /**
     * 数据
     */
    @Schema(description = "数据")
    private T data;

    public CommonResult(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }


    /*========================================= success*/
    public static <T> CommonResult<T> success() {
        return restResult(SUCCESS, "", null);
    }

    public static <T> CommonResult<T> success(T data) {
        return restResult(SUCCESS, "", data);
    }

    public static <T> CommonResult<T> success(String msg, T data) {
        return restResult(SUCCESS, msg, data);
    }

    public static <T> CommonResult<T> success(Integer code, String msg, T data) {
        return restResult(code, msg, data);
    }

    public static <T> CommonResult<T> success(TypicalCode statusEnum, T data) {
        return restResult(data, statusEnum);
    }


    /*========================================= error*/
    public static <T> CommonResult<T> error(Integer code, String message) {
        return restResult(code, message);
    }

    public static <T> CommonResult<T> error(String message) {
        return restResult(FAIL, message);
    }

    public static <T> CommonResult<T> error(TypicalCode statusEnum) {
        return restResult(statusEnum.getCode(), statusEnum.getMessage());
    }



    /**
     * 自定义状态、返回消息
     */
    private static <T> CommonResult<T> restResult(Integer code, String msg, T data) {
        return new CommonResult<>(code, msg, data);
    }

    /**
     * 自定义状态、返回消息
     */
    private static <T> CommonResult<T> restResult(Integer code, String msg) {
        return new CommonResult<>(code, msg);
    }

    /**
     * 使用枚举状态、返回消息
     */
    private static <T> CommonResult<T> restResult(T data, TypicalCode code) {
        return new CommonResult<>(code.getCode(), code.getMessage(), data);
    }

}
